package ngames.com.sushitv.net.okhttp.callback;

import org.json.JSONException;

import java.io.IOException;

import ngames.com.sushitv.api.ApiResponse;
import ngames.com.sushitv.core.ErrorEvent;
import ngames.com.sushitv.tools.LogUtil;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/1/19.
 */
public abstract class RequestCallBackJSON<T> extends RequestCallBack<T> {
    ApiResponse<T> mApiResponse;
    String mCode;

    @Override
    public T parseResponse(Response response) {
        try {
            String responseStr = response.body().string();
            LogUtil.d("RequestCallBackJSON", "responseStr:" + responseStr);
            try {
                mApiResponse = onParse(responseStr);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (mApiResponse != null) {
                mCode = mApiResponse.getCode();
            } else {
                mCode = ErrorEvent.CODE_ERROR_RESOLVE;
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
            mCode = ErrorEvent.CODE_ERROR_REQUEST;
        } catch (IOException e) {
            e.printStackTrace();
            mCode = ErrorEvent.CODE_ERROR_REQUEST;
        }
        beforeResult(mApiResponse);
        if(ErrorEvent.CODE_SUCCESS.equals(mCode)) {
            T obj = mApiResponse.getObj();
            success(obj == null ? mApiResponse.getObjList() : obj);
        } else {
            String msg = null;
            if(mApiResponse != null){
                msg = mApiResponse.getMsg();
            }
            failure(mCode, msg);
        }
        return null;
    }

    public abstract ApiResponse<T> onParse(String responseStr) throws JSONException;

    /**
     * 子线程解析之后，通知结果之前
     */
    public void beforeResult(ApiResponse<T> apiResponse) {

    }
}
